package com.zsj.qzt_punch.script;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.zsj.qzt_punch.http.QztHttpRequest;
import com.zsj.qzt_punch.pojo.*;
import com.zsj.qzt_punch.service.QztTokenInfoService;
import com.zsj.qzt_punch.service.impl.QztTokenInfoServiceImpl;
import com.zsj.qzt_punch.util.GetTokenQzt;
import com.zsj.qzt_punch.util.SendEmail;
import lombok.extern.slf4j.Slf4j;
import okhttp3.ResponseBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

import javax.annotation.Resource;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;


/**
 * @author zsj
 * @time 2022/11/2
 * <p>
 */
@Component
@Slf4j
@Configuration
@EnableScheduling
public class PunchScript {


    @Autowired
    QztTokenInfoService qztTokenInfoService ;

    public static int REQUEST_SUCCESSFUL_COUNT = 0;
    Retrofit retrofit;//网络请求
    public static Result result;//结果对象
    private static SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//时间格式化工具

    /**
     * 打卡
     * 周一 到 周五早上 8.30
     * 周一 到 周五下午 17.05
     */
//    @Scheduled(initialDelay = 5000,fixedDelay = 100000)
    @Scheduled(cron = "0 30 8 ? * MON-FRI")
    @Scheduled(cron = "0 5 17 ? * MON-FRI")
    public void punchClock() throws InterruptedException {
        log.info("请耐心等待8-10秒来等待获取到token值或更新~");
        Thread.sleep(8000);//保证token的读取完毕
        QueryWrapper<QztTokenInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name","数据库字典的名字");
        QztTokenInfo zsj = qztTokenInfoService.getOne(wrapper);
        retrofit = new Retrofit.Builder()
                .baseUrl(QztHttpRequest.baseUrl)
                .addConverterFactory(GsonConverterFactory.create()).build();
        QztHttpRequest qztHttpRequest = retrofit.create(QztHttpRequest.class);
        PunchClockRequestBody requestBody = new PunchClockRequestBody();
        //以下内容抓包可得
        requestBody.setLatitude(经度);
        requestBody.setCheckRange(500);
        requestBody.setLongitude(纬度);
        requestBody.setLocationName("地址");
        requestBody.setLatitude2("经度");
        requestBody.setLongitud2("纬度");
        requestBody.setLocationCode("");
        requestBody.setListPhoto(new ArrayList<>());
        qztHttpRequest.punch(zsj.getTokenValue(), requestBody)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd hh:mm:ss").create();
                        if (response.body() != null) {
                            try {
                                String json = response.body().string();
                                result = gson.fromJson(json, Result.class);
                                if (result.getMsg().contains("打卡成功")) {
                                    log.info(result.getMsg());
                                    //发送邮件
                                    SendEmail.sendEmail(result.getMsg() + ",打卡时间为" + format.format(new Date())
                                            +",\n\n\n\n------来自zsj的punchScript程序");
                                    REQUEST_SUCCESSFUL_COUNT++;
                                } else {
                                    log.warn(result.getMsg() + result.getCode());
                                }
                            } catch (Exception e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                        log.error("打卡失败,请求出现错误:{}", throwable.getMessage());
                    }
                });
    }
}
